from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.shortcuts import reverse
from utils import mymodel
from utils.pagnator import MyPaginator


# Create your views here.

def index(request):
    # print(request.path)
    # print(request.method)
    # print(request.encoding)
    # print(request.META['REMOTE_ADDR'])  #
    #
    # response = HttpResponse("这是首页app1")
    # # Content-Type: text/html
    # # response['Content-Type'] = 'application/octet-stream'
    # response['Content-Type'] = 'text/html; charset=utf-8'
    return redirect("app1:show_students")


def demo01(request):
    return render(request, 'demo01.html')  # 渲染


def demo02(request):
    return render(request, 'demo02.html', {"name": 'rose'})  # 渲染


def demo03(request):
    """
    测试模板查找的顺序
    :param request:
    :return:
    """
    return render(request, 'demo01.html')  # 渲染


def demo_list(request):
    # return render(request, 'demo_list.html', context={'students': ['张三', '李四', '杰克', 'rose']})
    return render(request, 'demo_list.html', context={'students': []})


def demo_dict(request):
    return render(request, 'demo_dict.html', {"person1": {"name": 'rose', 'gender': "男", 'age': 18}})


def demo_obj(request):
    kkx = mymodel.Teacher('卡卡西', 32, '男', hobby=["看书", '做任务', '敲代码'])
    return render(request, 'demo_obj.html', {'teacher': kkx})


def demo_list2(request):
    t1 = mymodel.Teacher('支老师', 30, '男', hobby=['沉默', '恐吓', '一个都别跑'])
    t2 = mymodel.Teacher('孔老师', 35, '男', hobby=['喂饭', 'dddd', '二级考试'])
    t3 = mymodel.Teacher('周老师', 20, '女', hobby=['哭', '梦魇', '缠腰打击'])

    return render(request, 'demo_list2.html', context={'teachers': [t1, t2, t3]})


def demo_empty(request):
    return render(request, 'demo_empty.html', {"students": [1, 2, 3]})


def demo_filter1(request):
    return render(request, 'demo_filter1.html', {"name": 'rOSe jobs'})


# -----------获取前端数据-----------------------

def getvalues(request):
    if 'HTTP_X_FORWARDED_FOR' in request.META:  # 获取用户真实IP地址
        user_ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        user_ip = request.META['REMOTE_ADDR']

    return render(request, 'getvalues.html', {'res': {'ip': user_ip}})


def book(request, bookname):
    return render(request, 'book.html', {'bookid': bookname})


def blog(request):
    # /blog/?id=2
    id = request.GET.get("id")
    name = request.GET.get("name")
    print(type(id))
    return render(request, 'blog1.html', {'blogid': id, "name": name})


# app1/login/kkk
# /kkk
#  在视图函数中 进行路由跳转
def login(request):
    if request.method == "GET":
        return render(request, 'login.html')

    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        print('username', username)
        print('password', password)
        # return HttpResponse("ok")
        # return redirect('/app1/index/')
        # return redirect('index')    # 根据路由名称 找到 路由的绝对路径
        # return redirect(reverse('index'))    # 路由反向解析
        # return redirect('app2:index', permanent=True)  # 路由反向解析
        return redirect("http://www.baidu.com")  # 路由反向解析


def book1(request, bookid):
    return HttpResponse(bookid)


def demo_test(request):
    # return redirect('app1:index')
    # return redirect('app1:book','红楼')
    # return redirect('app1:book',bookname='红楼')
    return render(request, 'demo_test.html')


def demo_extends(request):
    return render(request, 'son01.html')


def showimg(request):
    return render(request, 'showimg.html')


import os
from ysm import settings

from utils.fileutils import saveupfile, saveupfilemd5


def login2(request):
    if request.method == "GET":
        return render(request, 'login2.html')

    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        fileobj = request.FILES.get('icon')
        # saveupfile(fileobj)
        saveupfilemd5(fileobj)
        return HttpResponse('ok')


def downfile(request, filename):
    """
    将纲手这个图片下载
    :param request:
    :return:
    """
    filename1 = os.path.join(settings.BASE_DIR, 'static', 'img', filename)
    with open(filename1, 'rb') as f:
        file = f.read()
    # response = HttpResponse(file)
    response = HttpResponse(file)
    # response['Content-Type'] = 'text/html; charset=utf-8' #
    response['Content-Type'] = 'application/octet-stream'  #
    response['Content-Disposition'] = 'attachment;filename="{}"'.format(filename)
    return response


from .models import Student


# 插入数据
def orm_operation(request):
    # name = models.CharField(max_length=20)
    # age = models.IntegerField(null=True)
    # gender
    # s = Student(name='鸣人', age=7, gender='1')
    # s.save()
    # Student.objects.create(name='佐助',age=8,gender='1')

    # 查询数据
    # 查某一条数据 id 是2
    # s1 = Student.objects.get(id=2)
    # print(s1)
    # print(type(s1))
    #
    # print(s1.name)
    # print(s1.age)

    # s = Student(name='', age=18, gender='1', phone='13300')
    # s.save()
    # s1 = Student.objects.get(age=18)
    # student_qs = Student.objects.filter(age__gte=17)  # greater than  equal
    # student_qs = Student.objects.filter(age__in=[18, ])  # less than  equal
    # student_qs = Student.objects.filter(name__contains='test') # 包含  模糊查询
    # student_qs = Student.objects.filter(name__icontains="Test").filter(phone__startswith='133').update(name='子路')  # ignore 忽略
    # print(student_qs)
    # student_qs = student_qs.filter(phone__startswith='133')
    # Student.objects.update(gender=0)
    # Student.objects.filter(id=4).delete()
    Student.objects.filter(id=3).update(name='子夏')

    # print(student_qs)
    # print(type(student_qs))  # <class 'django.db.models.query.QuerySet'>

    return HttpResponse("更新成功")


from .models import Info


def info(request):
    """
    收集信息
    :param request:
    :return:
    """
    if request.method == "GET":
        # 返回一个收集界面
        return render(request, 'info.html')
    elif request.method == "POST":
        # 获取传过来的信息
        name = request.POST.get("name")
        completed = request.POST.get("completed")
        whole = request.POST.get("whole")

        # 写到数据库
        i = Info(name=name, completed=completed, whole=whole)
        i.save()

        return HttpResponse("感谢参与!")


def collect_student_info(request):
    if request.method == "GET":
        return render(request, 'collect_student_info.html')
    elif request.method == "POST":
        name = request.POST.get("name")
        age = request.POST.get("age")
        gender = request.POST.get("gender")
        phone = request.POST.get("phone")

        Student.objects.create(name=name, age=age, gender=gender, phone=phone)

        # return HttpResponse("插入成功")
        return redirect("app1:show_students")


#
# def show_students(request):
#     """
#     展示所有学生信息
#     :return:
#     """
#     # ?page = 2 & page_size = 5
#     page = request.GET.get('page', 1)
#     page_size = request.GET.get('page_size', 10)
#     try:
#         page = int(page)
#         if page < 1:
#             page = 1
#     except:
#         page = 1
#
#     try:
#         page_size = int(page_size)
#     except:
#         page_size = 10
#     students = Student.objects.all()  # 从数据库中把数据读出来
#     mypaginator = MyPaginator(students, page_size)
#
#     if page > mypaginator.max_page():
#         page = mypaginator.max_page()
#     students = mypaginator.get_pagex(page)
#
#     return render(request, 'show_students.html',
#                   {"students": students, 'curpage': page, "max_page": mypaginator.max_page(),
#                    "page_size": page_size})  # 数据+ 样式
#
#

from django.core.paginator import Paginator


def show_students(request):
    """
    展示所有学生信息 用django自带的分页器
    :return:
    """

    # ?page = 2 & page_size = 5
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    try:
        page = int(page)
        if page < 1:
            page = 1
    except:
        page = 1
    try:
        page_size = int(page_size)
    except:
        page_size = 10
    students = Student.objects.all()  # 从数据库中把数据读出来
    paginator = Paginator(students, page_size)
    print(paginator.num_pages)  # 最大的页码
    # print(paginator.count)
    if page > paginator.num_pages:
        page = paginator.num_pages

    # students = mypaginator.get_pagex(page)
    pagex = paginator.page(page)
    students = pagex.object_list
    return render(request, 'show_students.html',
                  {"students": students, 'curpage': page, "max_page": paginator.num_pages,
                   "page_size": page_size})  # 数据+ 样式


def student(request, student_id):
    try:
        s1 = Student.objects.get(id=student_id)
    except:
        s1 = ''

    return render(request, 'student.html', {"student": s1})


def student2(request):
    student_id = request.GET.get("id", 0)
    try:
        s1 = Student.objects.get(id=student_id)
    except:
        s1 = ''

    return render(request, 'student.html', {"student": s1})


def del_student(request, student_id):
    try:
        s1 = Student.objects.get(id=student_id)
        s1.delete()
        # return HttpResponse("删除成功")
        return redirect("app1:show_students")
    except:
        return HttpResponse("没有这个学生")


def del_student2(request):
    student_id = request.GET.get("id", 0)
    try:
        s1 = Student.objects.get(id=student_id)
        s1.delete()
        # return HttpResponse("删除成功")
        return redirect("app1:show_students")
    except:
        return HttpResponse("没有这个学生")


def update_student(request):
    if request.method == "GET":
        student_id = request.GET.get('id')
        # 查询数据库
        student = Student.objects.get(id=student_id)
        return render(request, 'update_student.html', {"student": student})
    elif request.method == "POST":
        student_id = request.POST.get('id')

        name = request.POST.get("name")
        age = request.POST.get("age")
        phone = request.POST.get("phone")
        gender = request.POST.get("gender")
        # student = Student.objects.get(id=student_id)
        # student.name = name
        # student.age = age
        # student.phone = phone
        # student.gender = gender
        # student.save()
        Student.objects.filter(id=student_id).update(name=name, age=age, gender=gender, phone=phone)

        return redirect("app1:show_students")


from faker import Faker
import random


# pip install Faker

def fun1(request):
    """
    生成一些学生的假数据 插入到数据库中
    :param request:
    :return:
    """
    fake = Faker(locale='zh_CN')
    objs = []
    for i in range(1, 6):
        s1 = Student(name=fake.name(), age=random.randint(15, 27),
                     gender=random.choice(["0", "1"]),
                     phone=fake.phone_number()
                     )

        objs.append(s1)
    Student.objects.bulk_create(objs)

    return HttpResponse('批量插入成功')


def query_student(request):
    if request.method == "POST":
        queryname = request.POST.get("queryname")
        students = Student.objects.filter(name__icontains=queryname)
        return render(request, 'query_result.html',
                      {"students": students})

